package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import model.Target;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.UserTransaction;

import ejb.TargetFacadeEJBRemote;

/**
 * Servlet implementation class Search
 */
@WebServlet("/Search")
public class Search extends HttpServlet {
	
	@PersistenceUnit
	EntityManagerFactory emf;

    @Resource private UserTransaction utx; 

	@PersistenceContext
	EntityManager em;   
	
	@EJB TargetFacadeEJBRemote targetf;
	
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Search() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
		//out.print("<html><body>");
		
		String search = (String)request.getParameter("search_box");
		
		try{
			utx.begin();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
				
		{		
		
		if(search!=null){

			try {
				ArrayList<Target> result= targetf.searchTarget(search);
				String number = targetf.getResultNum(result);
	            request.setAttribute("search_result", result);
	            request.setAttribute("result_num", number);
	            request.getRequestDispatcher("Home").forward(request, response);
	        } catch (Exception e) {
	        	e.printStackTrace();
	        }
			
		}else{
			out.print("Please access this page via normal way...");
			response.setHeader("Refresh","2;URL=home.jsp");		
		}
		
		}

		try{
			utx.commit();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		

	}

}
